'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import {
  User,
  Shield,
  ShieldCheck,
  Ban,
  RefreshCw,
  Mail
} from 'lucide-react'
import { adminApi } from '@/lib/api-client'

interface UserData {
  id: string
  email: string
  name: string
  avatar?: string
  role: 'USER' | 'ADMIN'
  createdAt: string
  _count: {
    tools: number
    reviews: number
    favorites: number
  }
}

export function UserManagement() {
  const [users, setUsers] = useState<UserData[]>([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState<'all' | 'admin' | 'user'>('all')

  useEffect(() => {
    fetchUsers()
  }, [])

  const fetchUsers = async () => {
    try {
      setLoading(true)
      const result = await adminApi.getUsers()

      if (result.success) {
        setUsers(result.data || [])
      }
    } catch (error) {
      console.error('获取用户列表失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleToggleRole = async (userId: string, currentRole: string) => {
    const newRole = currentRole === 'ADMIN' ? 'USER' : 'ADMIN'
    
    if (!confirm(`确定要将用户角色更改为${newRole === 'ADMIN' ? '管理员' : '普通用户'}吗？`)) {
      return
    }

    try {
      const response = await fetch(`/api/admin/users/${userId}/role`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ role: newRole }),
      })

      if (response.ok) {
        await fetchUsers()
      }
    } catch (error) {
      console.error('更新用户角色失败:', error)
    }
  }

  const filteredUsers = users.filter(user => {
    switch (filter) {
      case 'admin':
        return user.role === 'ADMIN'
      case 'user':
        return user.role === 'USER'
      default:
        return true
    }
  })

  if (loading) {
    return (
      <div className="space-y-4">
        {Array.from({ length: 3 }).map((_, i) => (
          <Card key={i} className="animate-pulse">
            <CardContent className="p-6">
              <div className="flex items-center gap-4">
                <div className="h-12 w-12 bg-gray-200 rounded-full"></div>
                <div className="flex-1">
                  <div className="h-4 bg-gray-200 rounded w-1/4 mb-2"></div>
                  <div className="h-3 bg-gray-200 rounded w-1/2"></div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 过滤器 */}
      <div className="flex gap-4">
        <Button
          variant={filter === 'all' ? 'default' : 'outline'}
          onClick={() => setFilter('all')}
        >
          全部用户 ({users.length})
        </Button>
        <Button
          variant={filter === 'admin' ? 'default' : 'outline'}
          onClick={() => setFilter('admin')}
        >
          管理员 ({users.filter(u => u.role === 'ADMIN').length})
        </Button>
        <Button
          variant={filter === 'user' ? 'default' : 'outline'}
          onClick={() => setFilter('user')}
        >
          普通用户 ({users.filter(u => u.role === 'USER').length})
        </Button>
        <Button variant="outline" onClick={fetchUsers}>
          <RefreshCw className="h-4 w-4 mr-2" />
          刷新
        </Button>
      </div>

      {/* 用户列表 */}
      <div className="space-y-4">
        {filteredUsers.length === 0 ? (
          <Card>
            <CardContent className="p-6 text-center">
              <p className="text-gray-500">暂无用户</p>
            </CardContent>
          </Card>
        ) : (
          filteredUsers.map((user) => (
            <Card key={user.id}>
              <CardContent className="p-6">
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-4">
                    {/* 用户头像 */}
                    <div className="h-12 w-12 bg-gradient-to-br from-blue-50 to-indigo-100 rounded-full flex items-center justify-center">
                      {user.avatar ? (
                        <img 
                          src={user.avatar} 
                          alt={user.name}
                          className="h-12 w-12 rounded-full object-cover"
                        />
                      ) : (
                        <User className="h-6 w-6 text-blue-400" />
                      )}
                    </div>

                    {/* 用户信息 */}
                    <div>
                      <div className="flex items-center gap-2">
                        <h3 className="font-semibold text-gray-900">{user.name}</h3>
                        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                          user.role === 'ADMIN' 
                            ? 'bg-purple-100 text-purple-800' 
                            : 'bg-gray-100 text-gray-800'
                        }`}>
                          {user.role === 'ADMIN' ? (
                            <>
                              <ShieldCheck className="h-3 w-3 mr-1" />
                              管理员
                            </>
                          ) : (
                            <>
                              <User className="h-3 w-3 mr-1" />
                              普通用户
                            </>
                          )}
                        </span>
                      </div>
                      <div className="flex items-center gap-1 text-sm text-gray-600 mt-1">
                        <Mail className="h-4 w-4" />
                        {user.email}
                      </div>
                      <div className="text-xs text-gray-500 mt-1">
                        注册时间: {new Date(user.createdAt).toLocaleDateString()}
                      </div>
                    </div>
                  </div>

                  {/* 操作按钮 */}
                  <div className="flex items-center gap-2">
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => handleToggleRole(user.id, user.role)}
                    >
                      {user.role === 'ADMIN' ? (
                        <>
                          <Shield className="h-4 w-4 mr-2" />
                          设为用户
                        </>
                      ) : (
                        <>
                          <ShieldCheck className="h-4 w-4 mr-2" />
                          设为管理员
                        </>
                      )}
                    </Button>
                  </div>
                </div>

                {/* 用户统计 */}
                <div className="mt-4 pt-4 border-t border-gray-200">
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div className="text-center">
                      <div className="font-semibold text-gray-900">{user._count.tools}</div>
                      <div className="text-gray-500">发布工具</div>
                    </div>
                    <div className="text-center">
                      <div className="font-semibold text-gray-900">{user._count.reviews}</div>
                      <div className="text-gray-500">评价数</div>
                    </div>
                    <div className="text-center">
                      <div className="font-semibold text-gray-900">{user._count.favorites}</div>
                      <div className="text-gray-500">收藏数</div>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))
        )}
      </div>
    </div>
  )
}
